import React, { Component } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Radio,
  Button,
  DatePicker,
  Space,
  Table,
  Tag,
  Image,
  Popconfirm,
  message,
} from 'antd'
import { Link } from 'react-router-dom'
import { articleListState } from 'api/constant'
import { getArticles, delArticle } from 'api/channel'
import defaultImg from 'assets/error.png'
import { articleStatus } from 'api/constant'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import MyChannel from 'components/MyChannel'

const { RangePicker } = DatePicker

export default class ArticleList extends Component {
  state = {
    channels: [],
    articles: [],
    currentPage: 1,
    pageSize: 10,
    total_count: 0,
    isLoading: false,
  }

  render() {
    const columns = [
      {
        title: '封面',
        dataIndex: ['cover'],
        render: ({ images, type }) => {
          if (type === 0) {
            return (
              <Image
                preview={false}
                width={200}
                height={150}
                src={defaultImg}
              />
            )
          }
          return (
            <Image
              width={200}
              height={150}
              src={images[0]}
              fallback={defaultImg}
            />
          )
        },
      },
      {
        title: '标题',
        dataIndex: 'title',
      },
      {
        title: '状态',
        dataIndex: 'status',
        render: (data) => {
          const tagObj = articleStatus[data]
          return <Tag color={tagObj.color}>{tagObj.text}</Tag>
        },
      },
      {
        title: '发布时间',
        dataIndex: 'pubdate',
      },
      {
        title: '阅读数',
        dataIndex: 'read_count',
      },
      {
        title: '评论数',
        dataIndex: 'comment_count',
      },
      {
        title: '点赞数',
        dataIndex: 'like_count',
      },
      {
        title: '操作',
        render: (data) => (
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => this.handleCircle(data.id)}
            ></Button>
            <Popconfirm
              title="你确定要删除文章吗"
              onConfirm={() => this.confirm(data)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="primary"
                shape="circle"
                danger
                icon={<DeleteOutlined />}
              ></Button>
            </Popconfirm>
          </Space>
        ),
      },
    ]
    return (
      <div className="articleList">
        <Card
          title={
            <Breadcrumb>
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>文章列表</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form initialValues={{ status: -1 }} onFinish={this.onFinish}>
            <Form.Item label="状态" name="status">
              <Radio.Group separator=">">
                {articleListState.map((item) => (
                  <Radio key={item.id} value={item.id}>
                    {item.name}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>
            <Form.Item label="频道" name="channel_id">
              <MyChannel></MyChannel>
            </Form.Item>
            <Form.Item label="日期" name="date">
              <RangePicker />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
            </Form.Item>
          </Form>
          <Card title={`根据筛选条件共查询到${this.state.total_count}条数据`}>
            <Table
              dataSource={this.state.articles}
              columns={columns}
              rowKey="id"
              loading={this.state.isLoading}
              pagination={{
                total: this.state.total_count,
                current: this.state.currentPage,
                pageSize: this.state.pageSize,
                onChange: this.changePages,
                pageSizeOptions: ['5', '10', '20', '50'],
              }}
            />
          </Card>
        </Card>
      </div>
    )
  }

  componentDidMount() {
    this.getArticleList()
  }
  handleCircle = (id) => {
    this.props.history.push('/home/publish/' + id)
  }

  // 获取文章列表
  async getArticleList(data) {
    this.setState({ isLoading: true, articles: [] })
    const {
      data: { results, total_count, page, per_page },
    } = await getArticles(data)
    this.setState({
      articles: results,
      total_count,
      currentPage: page,
      pageSize: per_page,
      isLoading: false,
    })
  }

  //分页改变
  changePages = async (page, pageSize) => {
    this.setState({ currentPage: page, pageSize })
    this.getArticleList({ ...this.data, page, per_page: pageSize })
  }

  // 点击筛选
  onFinish = (val) => {
    const data = {}
    if (val.status !== -1) {
      data.status = val.status
    }
    if (val.channel_id) {
      data.channel_id = val.channel_id
    }
    if (val.date) {
      data.begin_pubdate = val.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
      data.end_pubdate = val.date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss')
    }
    data.page = 1
    this.data = data
    this.getArticleList(data)
  }

  //点击删除
  confirm = async (data) => {
    const { currentPage, pageSize } = this.state
    await delArticle(data.id)
    if (this.state.articles.length === 1) {
      this.getArticleList({
        ...this.data,
        page: currentPage - 1,
        per_page: pageSize,
      })
      return message.success('删除成功')
    }
    this.getArticleList({ ...this.data, page: currentPage, per_page: pageSize })
    message.success('删除成功')
  }
}
